<?php
/**
 * 微信小程序接口类
 *  app id    wx51fa2f9eabf66605
 *  secert:   1d3e10ce3ea7da269e10f7805564d2c9
 */

namespace App\Libs\WeChat;

use App\Libs\Cos;
use App\Libs\qCould\CosClient;
use App\Libs\Util;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Ixudra\Curl\Facades\Curl;

class WxSmallClient
{
    private static $WX_URL = 'https://api.weixin.qq.com';

    // 微信公众平台access_token
    const wechat_open = 'wx_access_token';

    // 小程序access_token
    const wechat_small = 'small_access_token';

    // 小程序appid，secret
    private static $SMALL_APP_ID = 'wx2cd918c20ffe652c';
    private static $SMALL_SECRET = 'a12dc5a793c5883e2eebae5b0ad6277e';

    // 公众号 appid，secret
    private static $WECHAT_APPID = 'wx6c157d026dceea76';
    private static $WECHAT_SECRET = '2bcd2b9f480f857eb62a85eb5fef1a7a';


    public static function getSessionKey($code)
    {
        if (empty($code)) {
            return false;
        }
        return Curl::to(self::$WX_URL . '/sns/jscode2session')
            ->withData([
                'appid' => self::$SMALL_APP_ID,
                'secret' => self::$SMALL_SECRET,
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ])
            ->get();
    }

    /**
     * 根据session_key解密用户数据
     */
    public static function decryptData($session_key, $iv, $datas)
    {
        include_once "BizCrypt/wxBizDataCrypt.php";
        $pc = new \WXBizDataCrypt(self::$SMALL_APP_ID, $session_key);

        $rs = $pc->decryptData($datas, $iv, $data);
        if ($rs == 0) {
            return $data;
        } else {
            return $rs;
        }
    }

    /**
     * 获取access_token
     * $type int 获取类型 1公众号 2小程序
     * @return mixed
     */
    public static function getAccessToken($hash_key)
    {
        $access_token = Redis::get($hash_key);
        if (!$access_token) {
            if ($hash_key == self::wechat_open) {
                $appid = self::$WECHAT_APPID;
                $secret = self::$WECHAT_SECRET;
            } else {
                $appid = self::$SMALL_APP_ID;
                $secret = self::$SMALL_SECRET;
            }
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $res = Curl::to($url)->get();
            $res = json_decode($res, 1);
            if (isset($res['access_token'])) {
                Redis::setex($hash_key, 7200, $res['access_token']);
                return $res['access_token'];
            } else {
                fun_respon(0, '获取token错误');
            }
        } else {
            return $access_token;
        }

    }


    /**
     * @param $code
     * 获取会员的用户信息
     */
    public static function getMember($code){
        $access_token = self::getAccessToken(self::wechat_open);
        $url = "https://api.weixin.qq.com/card/membercard/userinfo/get?access_token={$access_token}";

        $stt = [
            'card_id' => "p2k0WuFqAtmaYGsdyE8-8C1rS9Es",
        ];
        $stt['code'] = $code;
        $res = Curl::to($url)
            //->withData((json_encode($str, JSON_UNESCAPED_UNICODE)))
            ->withContentType('application/json')
            ->withData($stt)
            ->asJsonRequest()
            ->post();
        $res = json_decode($res);
        return $res;
    }



    public static function updateMember($code,$record_bonus,$add_bonus){
        $access_token = self::getAccessToken(self::wechat_open);

        $url = "https://api.weixin.qq.com/card/membercard/updateuser?access_token={$access_token}"; //更新卡券

        $stt = [
            'card_id' => "p2k0WuFqAtmaYGsdyE8-8C1rS9Es",
        ];
        $stt['code'] = $code;
        $stt['record_bonus'] = $record_bonus;
        $stt['add_bonus'] = $add_bonus; //本次积分变动值，传负数代表减少
        $res = Curl::to($url)
            //->withData((json_encode($str, JSON_UNESCAPED_UNICODE)))
            ->withContentType('application/json')
            ->withData((json_encode($stt,320)))
            //->asJsonRequest()
            ->post();
        $res = json_decode($res);
        return $res;
    }


    public static function createdMemberCard()
    {
        $access_token = self::getAccessToken(self::wechat_open);
        $url = "https://api.weixin.qq.com/card/update?access_token={$access_token}"; //更新卡券
        //$url = "https://api.weixin.qq.com/card/delete?access_token={$access_token}"; //删除卡券

        $stt =
            ['card_id' => "p2k0WuFqAtmaYGsdyE8-8C1rS9Es",
                'member_card' =>
                    [   "background_pic_url"=>"http://mmbiz.qpic.cn/mmbiz_jpg/a8aUz8FLWxiauibmHGSOwYgC9Xq2thljLuBbb53icqNmia3UUtV6uurKGlHBVUH7UkVH7oxicvB2yYXSfsictu2ibkPLw/0",
                        'base_info' =>
                        [   'logo_url' => 'http://mmbiz.qpic.cn/mmbiz_jpg/a8aUz8FLWxjZpElCfeamwnsPwkFCLBuYiaOicLIg5zCL3wxarfJAQNSFLvziaH2w8iaT5Wv20peeia7kY0Nq4GsIlCw/0',
                            //'color' => 'Color010',
                             //'notice' => '卡券使用提醒，字数上限为16个汉字。',
                            //'description' => '卡券使用说明，字数上限为1024个汉字。ssssss',
                            //'date_info' => ['type' => 'DATE_TYPE_PERMANENT']
                        ],
//                        'prerogative' => '会员卡特权说明,限制1024汉字。',
//                        'supply_bonus' => true, //显示积分，填写true或false，如填写true，积分相关字段均为必 填 若设置为true则后续不可以被关闭。
//                        'supply_balance' => false,//是否支持储值，填写true或false。如填写true，储值相关字段均为必 填 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用， 详情见： 获取特殊权限
//                        'custom_cell1' => [
//                            'name' => '使用入口2',
//                            'tips' => '激活后显示',
//                            'url' => 'http://www.xxx.com'
//                        ]
                    ],
            ];

        /*$stt = [
            "card_id"=> "p2k0WuFqAtmaYGsdyE8-8C1rS9Es"
        ];*/



        var_dump($access_token);
        var_dump(json_encode($stt, JSON_UNESCAPED_UNICODE));
        $res = Curl::to($url)
            //->withData((json_encode($str, JSON_UNESCAPED_UNICODE)))
            ->withContentType('application/json')
            ->withData($stt)
            ->asJsonRequest()
            ->post();
        $res = json_decode($res);
        var_dump($res);
        exit;
        if (!isset($res->errcode) || $res->errcode != 0) fun_respon(0, '获取票券失败');

    }


    /**
     * 获取卡券签名
     * @param $card_id 卡券ID
     * @return array
     */
    public static function cardSign($card_id)
    {
        $access_token = self::getAccessToken(self::wechat_open);
        $ticket = Redis::get('wx_ticket');
        if (!$ticket) {
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=wx_card";
            $res = Curl::to($url)->get();
            $res = json_decode($res);
            if (!isset($res->errcode) || $res->errcode != 0) fun_respon(0, '获取票券失败');
            Redis::setex('wx_ticket', 7200, $res->ticket);
            $ticket = $res->ticket;
        }
        $timestamp = (string)time();
        $nonce_str = str_random(16);

        $param = [$timestamp, $nonce_str, $card_id, $ticket];
        sort($param);
        $sign = sha1(implode('', $param));
        return [
            'timestamp' => $timestamp,
            'nonce_str' => $nonce_str,
            'card_id' => $card_id,
            'sign' => $sign,
        ];
    }

    /**
     * 核销卡券
     * @return mixed
     */
    public static function unsetcode($encode, $card_id)
    {
        $access_token = self::getAccessToken(self::wechat_open);

        // 通过加密code获取解密之后的code
        $url = "https://api.weixin.qq.com/card/code/decrypt?access_token=" . $access_token;
        /*$res = Curl::to( $url )
            ->withContentType('application/json')
            ->withData(["encrypt_code"=>$encode])
            ->post();*/
        $res = fun_curl_header($url, json_encode(["encrypt_code" => $encode]));
        savelog('uncode', 'url:' . $url . "\n" . 'respon:' . $res . "\naccess_token:" . $access_token . "\nencode:" . $encode);
        $res = json_decode($res, 1);
        if (!isset($res['errcode']) || $res['errcode'] != 0) {
            fun_respon(0, '解码卡券code失败');
        }
        //$param = ['card_id'=>$card_id, 'code'=>$res['code']];
        // 非自定义code 只需要传入code
        $param = ['code' => $res['code']];
        $url = "https://api.weixin.qq.com/card/code/consume?access_token=" . $access_token;
        /*$res = Curl::to( $url )
            ->withContentType('application/json')
            ->withData($param)
            ->post();*/
        $res = fun_curl_header($url, json_encode($param));
        savelog('uncode', $res);
        $res = json_decode($res, 1);
        return $res;
    }


    public static function derypt($encode){
        $access_token = self::getAccessToken(self::wechat_open);
        // 通过加密code获取解密之后的code
        $url = "https://api.weixin.qq.com/card/code/decrypt?access_token=" . $access_token;
        /*$res = Curl::to( $url )
            ->withContentType('application/json')
            ->withData(["encrypt_code"=>$encode])
            ->post();*/
        $res = fun_curl_header($url, json_encode(["encrypt_code" => $encode]));
        savelog('uncode', 'url:' . $url . "\n" . 'respon:' . $res . "\naccess_token:" . $access_token . "\nencode:" . $encode);
        $res = json_decode($res, 1);
        if (!isset($res['errcode']) || $res['errcode'] != 0) {
            fun_respon(0, '解码卡券code失败');
        }
        //$param = ['card_id'=>$card_id, 'code'=>$res['code']];
        // 非自定义code 只需要传入code
        return $res['code'];
    }

    /**
     * 生成二维码
     * @param $param
     */
    public static function qrcode($param)
    {
        // 本地文件上传
        /*$token = self::getAccessToken(self::wechat_small);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$token;
        $data = ['scene'=>$param, 'page'=>'pages/home/activity/activity'];
        //$data = ['page'=>'pages/activity/activity?job_id='.$job_id.'&activity_id='.$activity_id, 'width'=>430];
        //$data = ['page'=>'pages/activity/activity', 'width'=>430];
        $res = fun_curl_header($url, json_encode($data), ['Content-Type:application/json']);
        $path = '/qrcode/';
        $tem_img = 'qrcode_'.str_random(16) . '.png';
        Storage::disk('qrcode')->put(
            $tem_img,
            $res,
            'public'
        );
        return $path.$tem_img;*/


        //  云存储

        $token = self::getAccessToken(self::wechat_small);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token;
        $data = ['scene' => $param, 'page' => 'pages/home/activity/activity'];
        //$data = ['page'=>'pages/activity/activity?job_id='.$job_id.'&activity_id='.$activity_id, 'width'=>430];
        //$data = ['page'=>'pages/activity/activity', 'width'=>430];
        $res = fun_curl_header($url, json_encode($data), ['Content-Type:application/json']);
        $path = 'qrcode/' . date('Y/m/');
        //$tem_img = 'qrcode_'.str_random(16) . '.png';
        $tem_img = 'qrcode_' . implode('_', explode('##', $param)) . '.png';
        $result = Cos::upload($res, $path . $tem_img);
        if ($result) {
            fun_respon(1, $result);
        }
        fun_respon(0, '生成二维码失败');
    }

    /**
     * @param $touser   openid
     * @param $data     模板数据
     * @param $formId   form_id
     * @param string $template_id 模板id
     * @param string $page 点击模板跳转地址
     * @return mixed
     */
    public static function sendTemplate($touser, $data, $formId, $template_id = '', $page = 'pages/home/activity/activity')
    {
        $token = self::getAccessToken(self::wechat_small);
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'page' => $page,
            'form_id' => $formId,
            'data' => $data,
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $token;
        $dataRes = Curl::to($url)
            ->withData(urldecode($json_template))
            ->post();
        $dataRes = json_decode($dataRes, true);
        return $dataRes;
    }

}